import {
  Event,
  Color,
  Material,
  defined,
  createPropertyDescriptor,
  Property,
} from "cesium";
import * as Cesium from "cesium";

/**
 * @name 定义线的轨迹动态线纹理
 * @param {color} 颜色
 * @param {count} 数量
 * @param {image} 图片
 * @param {duration} 迭代时间
 */
function PolylineTrailLinkMaterialProperty({ color, duration, count, image }) {
  this._definitionChanged = new Event();
  this._color = undefined;
  this._colorSubscription = undefined;
  this.color = color;
  this.count = count;
  this.image = image;
  this.duration = duration;
  this._time = new Date().getTime();
}
Object.defineProperties(PolylineTrailLinkMaterialProperty.prototype, {
  isConstant: {
    get: function () {
      return false;
    },
  },
  definitionChanged: {
    get: function () {
      return this._definitionChanged;
    },
  },
  color: createPropertyDescriptor("color"),
});
PolylineTrailLinkMaterialProperty.prototype.getType = function (time) {
  return "PolylineTrailLink";
};
PolylineTrailLinkMaterialProperty.prototype.getValue = function (time, result) {
  if (!defined(result)) {
    result = {};
  }
  result.color = Property.getValueOrClonedDefault(
    this._color,
    time,
    Color.WHITE,
    result.color
  );
  result.image = Material.PolylineTrailLinkImage;
  result.time =
    ((new Date().getTime() - this._time) % this.duration) / this.duration;
  return result;
};
PolylineTrailLinkMaterialProperty.prototype.equals = function (other) {
  return (
    this === other ||
    (other instanceof PolylineTrailLinkMaterialProperty &&
      Property.equals(this._color, other._color))
  );
};
// 在Material上挂载相关的流动线纹理 可以根据自己的需要进行封装
Cesium.PolylineTrailLinkMaterialProperty = PolylineTrailLinkMaterialProperty;
Material.PolylineTrailLinkType = "PolylineTrailLink";
Material.PolylineTrailLinkImage = "/bx-dashboard/imgs/line/spriteline.png";
// 定义着色器源码 核心部分
Material.PolylineTrailLinkSource =
  "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
    {\n\
        czm_material material = czm_getDefaultMaterial(materialInput);\n\
        vec2 st = materialInput.st;\n\
        vec4 colorImage = texture2D(image, vec2(fract(st.s - time), st.t));\n\
        material.alpha = colorImage.a;\n\
        material.diffuse = colorImage.rgb;\n\
        return material;\n\
    }";
Material._materialCache.addMaterial(Material.PolylineTrailLinkType, {
  fabric: {
    type: Material.PolylineTrailLinkType,
    uniforms: {
      color: new Color(0.0, 0.0, 1.0, 0.5),
      image: Material.PolylineTrailLinkImage,
      time: 0,
      count: 2,
    },
    source: Material.PolylineTrailLinkSource,
  },
  translucent: function (material) {
    return true;
  },
});
